package com.xssq.mvc;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.reflections.Reflections;

import com.xssq.mvc.annotation.Controller;
import com.xssq.mvc.annotation.Request;

public class ControllerResovler {
	
	private static Map<Requester, Handler> handlerMapping = new HashMap<>();
	
	/**
	 * 解析控制器注解
	 */
	public static void resolve() {
		Reflections reflections = new Reflections();
		Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(Controller.class);
		if (CollectionUtils.isEmpty(controllers)) return;
		
		for (Class<?> ctrl : controllers) {
			Method[] methods = ctrl.getDeclaredMethods();
			
			if (ArrayUtils.isEmpty(methods)) {
				continue;
			}
			
			for (Method method : methods) {
				handleMethod(ctrl, method);
			}
		}
	}
	
	/**
	 * 解析控制器方法上的注解
	 * @param ControllerClass
	 * @param method
	 */
	private static void handleMethod(Class<?> ControllerClass, Method method) {
		if (method.isAnnotationPresent(Request.Get.class)) {
			handlerMapping.put(new Requester("GET", method.getAnnotation(Request.Get.class).value()), 
					new Handler(ControllerClass, method));
		} else if (method.isAnnotationPresent(Request.Post.class)) {
			handlerMapping.put(new Requester("POST", method.getAnnotation(Request.Post.class).value()), 
					new Handler(ControllerClass, method));
		}
	}
	
	public static Map<Requester, Handler> getHandlerMapping() {
		return handlerMapping;
	}
	
}
